# database.py
from typing import Optional, List
from sqlmodel import Field, SQLModel, create_engine, Session
from datetime import datetime
import json
from config import settings
from sqlalchemy import JSON  # 添加 JSON 类型的导入


class DeploymentLog(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    timestamp: datetime = Field(default_factory=datetime.now)
    trigger_type: str = Field(index=True)  # e.g., "webhook", "manual"
    status: str = Field(index=True)  # e.g., "pending", "success", "failed"
    output: Optional[str] = None
    error_message: Optional[str] = None
    duration_seconds: Optional[float] = None

    # Optional fields from webhook payload
    repo_name: Optional[str] = None
    branch: Optional[str] = None
    commit_id: Optional[str] = None
    commit_message: Optional[str] = None
    committer_name: Optional[str] = None

    # Store the full webhook payload for debugging if needed
    webhook_payload_json: Optional[str] = Field(default=None, sa_column=JSON)

    class Config:
        json_dumps = json.dumps
        json_loads = json.loads



# Create an engine to interact with the database
# connect_args={"check_same_thread": False} is needed for SQLite with FastAPI
# because SQLite only allows one thread to access it at a time.
# FastAPI uses multiple threads for requests.
# 确保这里使用了 settings.database_url
engine = create_engine(settings.database_url, echo=False, connect_args={"check_same_thread": False})

def create_db_and_tables():
    """Creates all SQLModel tables in the database."""
    SQLModel.metadata.create_all(engine)


def get_session():
    """Dependency to get a database session."""
    with Session(engine) as session:
        yield session

